require(["common", "coAjax", "queryString", "href", "hash_routie", "Cookies"], function(jSouper, coAjax, QueryString, href, hash_routie, Cookies) {
	/*
	 * 请求购物车数据
	 */
	function _get_cart_success(result){
		var cart_detail = result.result;

		App.set("user.cart_detail",cart_detail);
		App.set("$Cache.cart.total_price",Model.Observer(function(){
			var cart_detail = App.get("user.cart_detail");
			var total_price = 0;
			cart_detail.forEach(function (cart) {
				cart.goods_info.forEach(function (goods_info) {
					total_price += goods_info.goods.price*goods_info.num;
				});
			});
			return total_price;
		}))
	};
	function _get_cart_error(errorCode,xhr,errorMsg){
		console.log("%c"+errorCode+": "+errorMsg,"color:orange;font-size:14px; text-shadow: 0 1px 0 #ccc;");
	};


	var queryString = new QueryString();
	var goods_id = queryString.get("goods_id");
	var recommender_id = queryString.get("rcid");

	if (goods_id) {
		coAjax.post(appConfig.user.cart,{
			goods_id:goods_id,
			num:queryString.get("num")
		},_get_cart_success,_get_cart_error);
	}else{
		coAjax.get(appConfig.user.get_cart_detail,_get_cart_success,_get_cart_error);
	}


	App.set("$Event.cart.cart_to_ach", function(e) {
		var cart_detail = App.get("user.cart_detail");
		var cart_id_list = jSouper.map(cart_detail, function(cart) {
			return cart._id;
		});

		coAjax.post(appConfig.user.cart_make_ach, {
			//user_address_id
			cart_id_list: cart_id_list,
			recommender_id: recommender_id,
		}, function(result) {
			console.log(result);
			href.jump("/m.pays.html#?ach_id=" + result.result._id)
		}, function(errorCode, xhr, errorMsg) {
			alert("error", errorMsg);
		});
	});
	App.set("$Event.cart.remove_goods", function(e, vm) {
		coAjax["delete"](appConfig.user.remove_goods_from_cart, {
			goods_id: vm.get("goods_id"),
			cart_id: vm.get("$Parent.$Parent._id")
		}, _get_cart_success, _get_cart_error)
	});
});